import { mapGetters } from "vuex";
import positionDialog from "@/components/positionDialog";
import propertyInformation from "./component/property-information";
import uploadMedia from "@/components/upload-media";
import BaseLoad from "@/assets/vue-mixin/BaseLoad";
import splitRoom from "../component/split-room";
import mergeRoom from "../component/merge-room";
import businessAdjustment from "../component/business-adjustment";
import {
    rentPropertyAdd,
    rentPropertyEdit,
    getRentProperty,
    rentPropertyRoomDelete,
    updateBusiness,
    validateProject,
    getReloadProperty
} from "../api/rentalProperty.js";
import {
    doSplit,
    doMerge,
    validateMerge
} from "~/views/property-info-sys/property-manage/api/room.js";
import { delFiles } from "~/views/property-info-sys/project-manage/api/project_manage";
import { doubleValidate, isInt, mapVerification } from "~/utils/validate.js";
import { validateLandCode } from "@/views/property-plan-sys/property-plan-manage/planning-property/api/planning.js";

let moment = require("moment");

export default {
    name: "rental_edit",
    components: {
        positionDialog,
        propertyInformation,
        uploadMedia,
        splitRoom,
        mergeRoom,
        businessAdjustment
    },
    mixins: [BaseLoad],
    created() {
        this.projectId = this.$route.query.projectId;
        if (this.projectId) {
            this.isAdd = false;
            this.handleGetRentProperty(this.projectId);
        }
        this.streets = this.getDict("streets");
        this.communityNames = this.getDict("community_names");
        this.manageUnits = this.getDict("administrative_office");
        this.landUses = this.getDict("land_uses");
        this.projectTypes = this.getDict("property_types");
        this.propertyUseTypes = this.getDict("property_use_types");
        this.propForm.rentProjectVo.cityCode = this.cityAssembly[0].value;
    },
    data() {
        return {
            isAdd: true,
            projectId: "",
            fileUploadUrl: "/admin/sys-file/upLodeFileEdit",
            modelType: "rent",
            flag: true,
            isRouterAlive: true,
            isComponentAlive: true,
						mergeDestroy: false,
            flagIndex: 0,
            uploadFileList: [],
            communityNameStreet: [],
            propForm: {
                rentProjectVo: {
                    cityCode: "",
                    countyCode: "",
                    projectStreet: "",
                    communityName: "",
                    addressInfo: "",
                    mapCoordinates: "",
                    propertyName: "",
                    usedName: "",
                    totalBuildings: "",
                    buildArea: "",
                    unmanagedArea: "",
                    managedArea: "",
                    manageUnit: "",
                    floorSpace: "",
                    areaCode: "",
                    areaName: "",
                    projectId: ""
                },
                rentLandVo: {
                    landId: "",
                    parcelNum: "",
                    parcelArea: "",
                    landUse: "",
                    landContractNum: "",
                    addressInfo: ""
                },
                rentPropertyVos: []
            },
            selectionList: [],
            streets: [],
            communityNames: [],
            manageUnits: [],
            landUses: [],
            projectTypes: [],
            propertyUseTypes: [],
            select: [],
            rentLandVo_rules: {
                parcelNum: [
                    {
                        required: false,
                        message: "请输入宗地号",
                        trigger: "blur"
                    },
                    {
                        min: 0,
                        max: 30,
                        message: "长度在0-30个字符串",
                        trigger: "blur"
                    }
                ],
                parcelArea: [{ validator: doubleValidate, trigger: "blur" }]
            },
            rentProjectVo_rules: {
                cityCode: [
                    {
                        required: true,
                        message: "请选择地址",
                        validator: (rules, value, callback) => {
                            //区县
                            let county = this.propForm.rentProjectVo.countyCode;
                            //   街道
                            let street = this.propForm.rentProjectVo
                                .projectStreet;
                            //   社区
                            let community = this.propForm.rentProjectVo
                                .communityName;
                            //   道路及门牌号
                            let address = this.propForm.rentProjectVo
                                .addressInfo;
                            if (
                                !value ||
                                !county ||
                                !street ||
                                !community ||
                                !address
                            ) {
                                return callback(new Error("物业地址不能为空"));
                            }
                            return callback();
                        },
                        trigger: "blur"
                    }
                ],
                mapCoordinates: [
                    {
                        required: true,
                        message: "请输入地图坐标",
                        trigger: "blur"
                    },
                    {
                        min: 0,
                        max: 50,
                        message: "长度在0-50个字符串",
                        trigger: "blur"
                    },
                    { validator: mapVerification, trigger: "blur" }
                ],
                propertyName: [
                    {
                        required: true,
                        message: "请输入项目名称",
                        trigger: "blur"
                    }
                ],
                /*usedName: [
                    { required: true, message: "请输入曾用名", trigger: "blur" }
                ],*/
                totalBuildings: [
                    {
                        required: true,
                        message: "请输入总栋数",
                        trigger: "blur"
                    },
                    { validator: isInt, trigger: "blur" }
                ],
                buildArea: [
                    {
                        required: true,
                        message: "请输入建筑面积",
                        trigger: "blur"
                    },
                    { validator: doubleValidate, trigger: "blur" }
                ],
                unmanagedArea: [{ validator: doubleValidate, trigger: "blur" }],
                managedArea: [{ validator: doubleValidate, trigger: "blur" }],
                floorSpace: [{ validator: doubleValidate, trigger: "blur" }]
            }
        };
    },
    computed: {
        ...mapGetters({
            cityAssembly: "getCityAssembly",
            districtCollection: "getDistrictCollection"
        })
    },
    methods: {
        // hxf-1016-区改变清空街道和社区
        handleChangeCountyCode() {
            this.propForm.rentProjectVo.projectStreet = "";
            this.propForm.rentProjectVo.communityName = "";
            this.propForm.rentProjectVo.addressInfo = "";
        },
        // hxf-1016-街道改变清空社区
        handleChangeStreet() {
            this.propForm.rentProjectVo.communityName = "";
            this.propForm.rentProjectVo.addressInfo = "";
            this.initCommunityName();
        },
        initCommunityName() {
            this.communityNameStreet.length = 0;
            let selectStreet = this.propForm.rentProjectVo.projectStreet;
            if (
                selectStreet != "" &&
                this.communityNames != null &&
                this.communityNames.length
            ) {
                this.communityNameStreet = this.communityNames.filter(
                    cn => cn.value.indexOf(selectStreet) != -1
                );
            }
        },
        // 监听地图坐标监听
        resetPosition(data) {
            try {
                let position = JSON.parse(data);
                if (position.length) {
                    this.propForm.rentProjectVo.mapCoordinates = position.join(
                        ","
                    );
                }
            } catch (e) {
                console.log(e);
            }
        },
        // hxf-1016-总栋数失焦校验
        handleTotalBuildings() {
            if (Number(this.propForm.rentProjectVo.totalBuildings) < 0) {
                this.$message.error("总栋数不能小于0！");
                this.propForm.rentProjectVo.totalBuildings = "";
            }
            if (Number(this.propForm.rentProjectVo.totalBuildings) > 99999) {
                this.$message.error("总栋数不能大于99999！");
                this.propForm.rentProjectVo.totalBuildings = "";
            }
        },
        // hxf-1016-回显时对应value显示label
        getCardTypeValue(num, sum) {
            let arr = sum.filter(e => e.value === num);
            if (arr.length > 0) {
                return arr[0].label;
            } else {
                return num;
            }
        },
        // hxf-1016-物业信息添加
        handleSuperAdd() {
            // console.log(this.propForm.rentPropertyVos)
            let selectionList = [];
            this.isComponentAlive = true;
            let SuperAdd = false;
            this.$nextTick(() =>
                this.$refs.propertyInformation.show(selectionList, SuperAdd)
            );
            this.flag = true;
            this.flagIndex = 0;
        }, // hxf-1016-物业信息编辑
        handleSuperEdit() {
            if (this.selectionList.length === 0) {
                this.$alert("请勾选要修改的数据！");
                return;
            }
            if (this.selectionList.length > 1) {
                this.$alert("单次操作只能修改一条数据！");
                return;
            }
            this.isComponentAlive = true;
            let SuperAdd = true;
            this.$nextTick(() => {
                this.$refs.propertyInformation.show(
                    JSON.parse(JSON.stringify(this.selectionList)),
                    SuperAdd
                );
            });
            this.flag = false;
            this.flagIndex = this.selectionList[0].serialNumber - 1;
        },
        // hxf-1016-物业信息删除
        handleSuperDelete() {
            if (this.selectionList.length === 0) {
                this.$alert("请勾选要删除的数据！");
                return;
            }
            let ids = this.selectionList.map(sd => sd.roomId);
            this.selectionList.map(item => {
                if (item.roomId === undefined) {
                    this.propForm.rentPropertyVos.splice(
                        item.serialNumber - 1,
                        1
                    );
                    this.isRouterAlive = false;
                    this.$nextTick(() => (this.isRouterAlive = true));
                    this.$message.success("删除成功");
                    this.selectionList = [];
                    this.propForm.rentPropertyVos.map((item, index) => {
                        this.propForm.rentPropertyVos[index].serialNumber =
                            index + 1;
                    });
                } else {
                    this.$confirm("此操作将永久删除该数据, 是否继续?", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    })
                        .then(() => {
                            rentPropertyRoomDelete(ids)
                                .then(rep => {
                                    this.$message.success("删除成功");
                                    this.handleGetRentProperty(this.projectId);
                                })
                                .catch(e => {
                                    console.log(e);
                                    this.$message.error("删除失败");
                                });
                        })
                        .catch(e => {
                            console.log(e);
                            this.$message.info("已取消删除");
                        });
                }
            });
        },
        // hxf-1016-物业信息多选选中
        selectionChange(val) {
            this.selectionList = val;
        },
        //hxf-1016-物业信息取消保存
        handleClickDoCancel() {
            this.isComponentAlive = false;
            this.selectionList = [];
            this.isRouterAlive = false;
            this.$nextTick(() => (this.isRouterAlive = true));
        },
        //hxf-1016-物业信息保存
        handleClickDoProperty(data) {
            let rentPropertyVos = {
                ...data.otherInformation,
                ...data.propertyInformation
            };
            // console.log(rentPropertyVos)
            if (this.flag) {
                this.propForm.rentPropertyVos.push(rentPropertyVos);
                this.propForm.rentPropertyVos.map((item, index) => {
                    this.propForm.rentPropertyVos[index].serialNumber =
                        index + 1;
                });
            } else {
                this.propForm.rentPropertyVos[this.flagIndex] = rentPropertyVos;
                this.isRouterAlive = false;
                this.$nextTick(() => (this.isRouterAlive = true));
                this.selectionList = [];
            }
        },
        // hxf-1016-物业信息时间格式化
        dataFormat(row, column, cellValue) {
            if (!cellValue) {
                return "";
            }
            return moment(cellValue).format("YYYY-MM-DD");
        },
        // hxf-1016-文件上传成功处理
        onSuccess(res, file, fileList) {
            if (res.data) {
                this.propForm.rentProjectVo.projectId = res.data;
                this.sendFormData(res.data);
            } else {
                this.err("提交失败");
            }
        },
        // hxf-1016-文件删除处理
        handleClean(fileId) {
            this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    delFiles(fileId, this.modelType).then(resp => {
                        if (resp.data.code === 0) {
                            this.$message({
                                type: "success",
                                message: "删除成功!"
                            });
                            this.files = this.files.filter(
                                file => file.fileId != fileId
                            );
                        } else {
                            this.$message({
                                type: "error",
                                message: "删除失败!"
                            });
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除"
                    });
                });
        },
        // hxf-1016-表单验证
        submitForm() {
            const rentProjectVo = new Promise((resolve, reject) => {
                this.$refs["propForm"].validate(valid => {
                    if (valid) resolve();
                });
            });
            const rentLandVo = new Promise((resolve, reject) => {
                this.$refs["rentLandVo"].validate(valid => {
                    if (valid) resolve();
                });
            });
            this.propForm.rentProjectVo.areaCode = this.propForm.rentProjectVo.cityCode + "-" + this.propForm.rentProjectVo.countyCode;
            this.propForm.rentProjectVo.areaName = this.getCardTypeValue(this.propForm.rentProjectVo.cityCode, this.cityAssembly)
                + this.getCardTypeValue(this.propForm.rentProjectVo.countyCode, this.districtCollection)
                + this.getCardTypeValue(this.propForm.rentProjectVo.projectStreet, this.streets)
                + this.getCardTypeValue(this.propForm.rentProjectVo.communityName, this.communityNames)
            if (this.isAdd) {
                validateProject({
                    addressInfo: this.propForm.rentProjectVo.addressInfo,
                    areaCode:
                        this.propForm.rentProjectVo.areaCode +
                        "-" +
                        this.propForm.rentProjectVo.projectStreet +
                        "-" +
                        this.propForm.rentProjectVo.communityName,
                    propertyName: this.propForm.rentProjectVo.propertyName
                }).then(res => {
                    if (res.data.data === 1) {
                        this.$message.error("该项目名称已存在，请重新输入！")
                    } else {
                        Promise.all([rentProjectVo, rentLandVo]).then(() => {
                            if (this.uploadFileList.length) {
                                if (!this.isAdd) {
                                    this.$refs.myUpload.submit(
                                        this.modelType,
                                        this.propForm.rentProjectVo.projectId
                                    );
                                } else {
                                    this.$refs.myUpload.submit(this.modelType);
                                }
                            } else {
                                this.sendFormData();
                            }
                        });
                    }
                })
            } else {
                validateProject({
                    addressInfo: this.propForm.rentProjectVo.addressInfo,
                    areaCode:
                        this.propForm.rentProjectVo.areaCode +
                        "-" +
                        this.propForm.rentProjectVo.projectStreet +
                        "-" +
                        this.propForm.rentProjectVo.communityName,
                    propertyName: this.propForm.rentProjectVo.propertyName,
                    projectId: this.projectId
                }).then(res => {
                    if (res.data.data === 1) {
                        return this.$message.error("该项目名称已存在，请重新输入！")
                    } else {
                        Promise.all([rentProjectVo, rentLandVo]).then(() => {
                            if (this.uploadFileList.length) {
                                if (!this.isAdd) {
                                    this.$refs.myUpload.submit(
                                        this.modelType,
                                        this.propForm.rentProjectVo.projectId
                                    );
                                } else {
                                    this.$refs.myUpload.submit(this.modelType);
                                }
                            } else {
                                this.sendFormData();
                            }
                        });
                    }
                })
            }
        },
        // hxf-1016-提交
        sendFormData() {
            if (this.isAdd) {
                this.loadAction("保存中");
                rentPropertyAdd(this.propForm)
                    .then(rep => {
                        this.loadClose();
                        this.$message.success("保存成功");
                        this.closeNowRouter();
                    })
                    .catch(e => {
                        console.log(e);
                        this.loadClose();
                        this.$message.error("保存失败");
                    });
            } else {
                this.loadAction("保存中");
                rentPropertyEdit(this.propForm)
                    .then(rep => {
                        this.loadClose();
                        this.$message.success("修改成功");
                        this.closeNowRouter();
                    })
                    .catch(e => {
                        console.log(e);
                        this.loadClose();
                        this.$message.error("修改失败");
                    });
            }
        },
        closeNowRouter() {
            //关闭当前新增页，暂时没找到好办法
            this.$store.commit("delHistoryRoute", this.$route.fullPath);
            // this.$parent.$children[2].closeTab('current')
            //跳转
            this.$router.push("/wy-lessor/property-management");
        },
        // hxf-1015-打开经营调整
        handleOpenBusiness() {
            if (this.selectionList.length === 0) {
                this.$alert("请勾选要修改的数据！");
                return;
            }
            if (this.selectionList.length > 1) {
                this.$alert("单次操作只能修改一条数据！");
                return;
            }
            this.selectionList.map(item => {
                if (item.roomId) {
                    this.$refs.businessAdjustment.show(this.selectionList);
                    this.flagIndex = this.selectionList[0].serialNumber - 1;
                } else {
                    this.$alert("未入库数据不能进行经营调整！");
                    return;
                }
            });
        },
        // hxf-1015-保存经营调整
        async handleBusinessAdjustment(data) {
            this.loadAction("调整中");
            await updateBusiness(data)
                .then(res => {
                    this.loadClose();
                    this.$message.success("调整成功！");
                    this.$refs.businessAdjustment.handleCancel();
                    if (data.businessOperationBefore === "10") {
                        this.propForm.rentPropertyVos[
                            this.flagIndex
                        ].operation = "20";
                    } else {
                        this.propForm.rentPropertyVos[
                            this.flagIndex
                        ].operation = "10";
                    }
                    this.isRouterAlive = false;
                    this.$nextTick(() => (this.isRouterAlive = true));
                    this.selectionList = [];
                })
                .catch(e => {
                    console.log(e);
                    this.loadClose();
                    this.$message.error("调整失败！");
                    this.$refs.businessAdjustment.handleCancel();
                });
        },
        //hxf-1016-打开物业拆分弹框
        handleOpenSplitRoom() {
            if (this.selectionList.length === 0) {
                this.$alert("请选择要拆分的物业信息！");
                return false;
            }
            if (this.selectionList.length > 1) {
                this.$alert("请勿选择多条房源进行拆分操作！");
                return false;
            }
						let noSplit = this.selectionList.find(item => item.propertyStatus != "10")
						if(noSplit){
							this.$alert("非空置状态下的物业不能进行拆分操作！");
							return false;
						}
						let noArea =  this.selectionList.find(sv => sv.buildingArea == 0 || sv.buildingArea == "" || sv.buildingArea == null);
						if (noArea) {
							this.$alert(
								"该物业没有建筑面积，不允许进行拆分操作！"
							)
							return false
						}
            this.selectionList.map(item => {
                if (item.roomId) {
                    this.$refs["splitRoom"].dialogVisible = true;
                    this.$refs["splitRoom"].sourceRoom = this.selectionList[0];
                    this.$refs["splitRoom"].fromData.roomInfo = [];
                    this.$refs["splitRoom"].active = 0;
                    let baseName = this.selectionList[0].propertyName;
                    if (
                        this.selectionList[0].splitMergeStatus === 1 ||
                        this.selectionList[0].splitMergeStatus === 2
                    ) {
                        this.$refs["splitRoom"].baseRoomName = baseName.slice(
                            0,
                            baseName.lastIndexOf("-")
                        );
                    } else {
                        this.$refs["splitRoom"].baseRoomName = baseName;
                    }
                } else {
                    this.$alert("未入库数据不能进行拆分！");
                    return;
                }
            });
        },
        //hxf-1016-执行物业拆分
        handleDoSplit(data) {
            this.loadAction("保存中");
            doSplit(data)
                .then(res => {
                    this.loadClose();
                    this.$message.success("保存成功！");
                    this.handleGetReloadProperty(this.projectId);
                })
                .catch(e => {
                    console.log(e);
                    this.loadClose();
                    this.$message.error("保存失败！");
                });
        },
        //hxf-1016-打开物业合并
        async handleOpenMergeRoom() {
            if (this.selectionList.length < 2) {
                this.$alert("请至少选择两个合并的物业信息！");
                return false;
            }
					let noSplit = this.selectionList.find(item => item.propertyStatus != "10")
					if (noSplit) {
						this.$alert("非空置状态下的物业不能进行拆分操作！");
						return false;
					}
            let spArr = this.selectionList.find(
                sv =>
                    sv.splitMergeStatus == "0" || sv.splitMergeStatus == "null"
            );
            if (spArr) {
                this.$alert("合并操作只能对已拆分的房源进行合并！");
                return false;
            }
            let baseName = this.selectionList[0].propertyName;
            let bn = baseName.slice(0, baseName.lastIndexOf("-"));

            let noEq = this.selectionList.find(
                sv => sv.propertyName.indexOf(bn) != 0
            );
            if (noEq) {
                this.$alert(
                    "选择的房源不满足合并条件，合并要求：某房源拆分后生成多个房源，合并操作只能在这多个房源中进行！"
                );
                return false;
            }
            let ids = this.selectionList.map(sv => {
                return sv.roomId;
            });
            let mergeFlag = false;
            await validateMerge({ roomIds: ids }).then(res => {
                mergeFlag = res.data.data === 0;
            });
            if (!mergeFlag) {
                this.$alert(
                    "选择的房源不满足合并条件，合并条件为【同一产权证下的同一栋楼、同一单元且同一楼层】！"
                );
                return false;
            }
						this.mergeDestroy = true
						this.$nextTick(() =>{
							this.$refs["mergeRoom"].dialogVisible = true;
							this.$refs["mergeRoom"].active = 0;
							this.$refs["mergeRoom"].sourceRoom = this.selectionList;
							this.$refs["mergeRoom"].baseRoomName = bn;
						})
        },
			//销毁合并物业组件
				mergeRoomClose(){
					this.mergeDestroy = false;
				},
        //hxf-1016-执行物业合并
        handleDoMerge(data) {
            this.loadAction("保存中");
            doMerge(data)
                .then(res => {
                    this.loadClose();
                    this.$message.success("合并成功！");
                    this.handleGetReloadProperty(this.projectId);
                })
                .catch(e => {
                    console.log(e);
                    this.loadClose();
                    this.$message.error("合并失败！");
                });
        },
        // hxf-1020-回显
        handleGetRentProperty(id) {
            getRentProperty(id).then(res => {
                if (res.data.code === 0 && res.data.data !== "") {
                    this.propForm = res.data.data;
                    this.propForm.rentProjectVo.cityCode = this.propForm.rentProjectVo.areaCode.split(
                        "-"
                    )[0];
                    this.propForm.rentProjectVo.countyCode = this.propForm.rentProjectVo.areaCode.split(
                        "-"
                    )[1];
                    this.propForm.rentPropertyVos.map((item, index) => {
                        this.propForm.rentPropertyVos[index].serialNumber =
                            index + 1;
                    });
                    this.$refs.myUpload.getFiles(id);
                    this.initCommunityName();
                }
            });
        },
        // hxf-1023-校验物业名称是否重复
        handleValidateProject(value) {
            if (
                this.propForm.rentProjectVo.cityCode === "" ||
                this.propForm.rentProjectVo.countyCode === "" ||
                this.propForm.rentProjectVo.projectStreet === "" ||
                this.propForm.rentProjectVo.communityName === ""
            ) {
                this.$message.error(
                    "请将市区街道社区填写完整后再填写详细地址！"
                );
                this.propForm.rentProjectVo.addressInfo = "";
            } else {
                let areaCode =
                    this.propForm.rentProjectVo.cityCode +
                    "-" +
                    this.propForm.rentProjectVo.countyCode +
                    "-" +
                    this.propForm.rentProjectVo.projectStreet +
                    "-" +
                    this.propForm.rentProjectVo.communityName;
                validateProject({
                    addressInfo: value,
                    areaCode: areaCode,
                    projectId: this.projectId
                }).then(res => {
                    if (res.data.data === 2) {
                        this.$message.warning("该地址已存在！");
                    }
                });
            }
        },
        landCodeOnly(value) {
            validateLandCode({
                landCode: value,
                landId: this.propForm.rentLandVo.landId || ""
            }).then(res => {
                if (res.data.data !== 0) {
                    this.$message.warning("宗地号已存在，请确认是否继续操作");
                }
            });
        },
        // hxf-1023-拆分、合并保存后数据查询
        handleGetReloadProperty(id) {
            getReloadProperty(id).then(res => {
                if (res.data.code === 0) {
                    this.propForm.rentPropertyVos = res.data.data;
                    this.propForm.rentPropertyVos.map((item, index) => {
                        this.propForm.rentPropertyVos[index].serialNumber =
                            index + 1;
                    });
                }
            });
        },
        // 经营面积失焦校验
        handleAreaCompared() {
            if (
                Number(this.propForm.rentProjectVo.unmanagedArea) +
                    Number(this.propForm.rentProjectVo.managedArea) >
                Number(this.propForm.rentProjectVo.buildArea)
            ) {
                this.$message.error(
                    "经营面积+非经营面积之和不能大于建筑面积！"
                );
                this.propForm.rentProjectVo.managedArea = "";
            }
        }
    }
};
